#include <SD.h>
#include <DHT.h>
DHT dht(2,22);
const int intervalo = 10*1000; 
long tiempoUltimaLectura = 0;  
long tiempoActual = 0;         
float h,t;       
              
void setup() {
  if (inicioSD() == true) {
     dht.begin();
  }
}

void loop(){
  tiempoActual = millis();
  if (tiempoActual > tiempoUltimaLectura + intervalo) {
    h = dht.readHumidity();
    t = dht.readTemperature();
    if (!isnan(t) || !isnan(h)) {
	 File mifichero = SD.open("datalog.csv", FILE_WRITE);
	 if (mifichero==true) {
	     mifichero.print(h);
	     mifichero.print("\t");  
	     mifichero.println(t);
	     mifichero.close();
	     tiempoUltimaLectura = millis();
	 }  
    }
}

boolean inicioSD() {
  boolean resultado = false;
  pinMode(10, OUTPUT); 
  if (SD.begin(4)==false) {
    resultado = false;
  } 
  else {
    File mifichero = SD.open("datalog.csv", FILE_WRITE);
    if (mifichero == true) {
      mifichero.println();
      mifichero.println("rH (%) \t temp. (*C)");
      mifichero.close();
      resultado = true;
    }
  }  
  return resultado;
}

